package com.sansan.qiangji.utils.tcpUtils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;

@Slf4j
public class YRTcpUtil {
    private Socket socket;
    private String ip;
    private InputStream inputStream;
    private OutputStream outputStream;
    private SocketAddress socketAddress;
    private static final int CONNECT_TIMEOUT = 3000;
    private static final int RECEIVE_TIMEOUT = 3000;

    public YRTcpUtil(String ip, int port) {
        this.ip = ip;
        socketAddress = new InetSocketAddress(ip, port);
    }

    /**
     * 关闭连接
     * */
    public void disConnect() {
        if (socket != null) {
            try {
                socket.shutdownOutput();
                socket.shutdownInput();
                socket.close();
            } catch (IOException ignored) {
            }
            socket = null;
        }
    }

    /**
     * 判断是否连接，未连接则重新连接
     * */
    public Boolean isConnect() {
        if (socket == null) {
            try {
                socket = new Socket();
                socket.connect(socketAddress, CONNECT_TIMEOUT);
            } catch (Exception ex) {
                disConnect();
                log.error("【有人TCP通信】TCP连接超时，IP={}", ip);
                return false;
            }
        }
        try {
            socket.sendUrgentData(0xFF);
        } catch (Exception ex) {
            disConnect();
            log.error("【有人TCP通信】TCP断开连接，IP={}", ip);
            return false;
        }
        return true;
    }

    /**
     * 查看版本号
     * */
    public String checkScanVer() {
        if (!isConnect()) {
            return null;
        }
        byte[] data = new byte[]{0x02, 0x02, 0x06, (byte) 0x82, 0x30, 0x30, 0x30, 0x41, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x70};
        try {
            outputStream = socket.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
        } catch (Exception ex) {
            disConnect();
            log.error("【TCP通信】发送数据失败，IP={}", ip);
            return null;
        }
        byte[] receiveData = new byte[1024];
        byte[] resultData;
        try {
            socket.setSoTimeout(RECEIVE_TIMEOUT);
            inputStream = socket.getInputStream();
            int i = inputStream.read(receiveData);
            resultData = new byte[i];
            System.arraycopy(receiveData, 0, resultData, 0, i);
        } catch (Exception ex) {
            disConnect();
            log.error("【TCP通信】接收数据超时，IP={}", ip);
            return null;
        }
        return new String(resultData, StandardCharsets.US_ASCII);
    }

    /**
     * 持续扫码
     * */
    public Boolean openScan() {
        if (!isConnect()) {
            return null;
        }
        byte[] data = new byte[]{0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, (byte) 0xF8};
        try {
            outputStream = socket.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
        } catch (Exception ex) {
            disConnect();
            log.error("【TCP通信】发送数据失败，IP={}", ip);
            return null;
        }
        return true;
    }

    /**
     * 接收扫码数据
     * */
    public String receiveScanData(int receiveTimeOut) {
        if (!isConnect()) {
            return null;
        }
        byte[] receiveData = new byte[1024];
        byte[] resultData;
        try {
            socket.setSoTimeout(receiveTimeOut);
            inputStream = socket.getInputStream();
            int i = inputStream.read(receiveData);
            resultData = new byte[i];
            System.arraycopy(receiveData, 0, resultData, 0, i);
        } catch (Exception ex) {
            disConnect();
            log.error("【TCP通信】接收数据超时，IP={}", ip);
            return null;
        }
        return new String(resultData, StandardCharsets.US_ASCII);
    }
}
